package com.qf.shiro.base.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zhangwei
 */
@RestController
@RequestMapping("/user")
public class SysUserController {
    /**
     * 安全 > 规范
     * 查询当前用户是否存在
     * 比对密码
     *
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/login")
    public String doLogin(String username, String password) {
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new UsernamePasswordToken(username, password));
        } catch (UnknownAccountException uae) {
            // 转化自定义异常
            throw new RuntimeException("账号密码错误");
        } catch (IncorrectCredentialsException ice) {
            // 转化成自定义异常
            throw new RuntimeException("账号密码错误");
        } catch (LockedAccountException lae) {
            throw new RuntimeException("账号被锁定");
        } catch (AuthenticationException ae) {
            throw new RuntimeException("登录失败");
        }
        return subject.getSession().getId().toString();
    }
}
